package com.qinggeng.project.system.service.impl;

import com.qinggeng.framework.config.mq.dto.MessagePresaleDTO;
import com.qinggeng.project.system.domain.Goods;
import com.qinggeng.project.system.domain.GoodsPresale;
import com.qinggeng.project.system.mapper.GoodsPresaleMapper;
import com.qinggeng.project.system.service.IGoodsPresaleService;
import com.qinggeng.project.system.service.IGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 吴鹏飞
 * @date 2020/11/28
 * 预售商品业务实现
 */
@Service
@Slf4j
public class IGoodsPresaleServiceImpl implements IGoodsPresaleService {
    @Resource
    private GoodsPresaleMapper goodsPresaleMapper;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private IGoodsService goodsService;

    private static final String PRESALE_MESSAGE_ID_LOCK="presale_message_id_lock";

    @Override
    public List<GoodsPresale> listGoodsPresale(GoodsPresale goodsPresale) {
        List<GoodsPresale> goodsPresaleList = goodsPresaleMapper.select(goodsPresale);
        return goodsPresaleList;
    }

    @Override
    public GoodsPresale getGoodsPresale(Long id) {
        GoodsPresale goodsPresale = goodsPresaleMapper.selectByPrimaryKey(id);
        return goodsPresale;
    }

    @Override
    public int insertGoodsPresale(GoodsPresale goodsPresale) {
        int i = goodsPresaleMapper.insertSelective(goodsPresale);
        return i;
    }

    @Override
    public int updateGoodsPresale(GoodsPresale goodsPresale) {
        int i = goodsPresaleMapper.updateByPrimaryKeySelective(goodsPresale);
        return i;
    }

    @Override
    public void deleteGoodsPresale(Long[] ids) {
        for (Long id : ids) {
            goodsPresaleMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public void updateGoodsPresaleGoodsType(MessagePresaleDTO messagePresaleDTO) {
        RLock lock = redissonClient.getLock(PRESALE_MESSAGE_ID_LOCK + messagePresaleDTO.getMessageId());
        lock.lock();
        try {
            Goods goods = goodsService.selectGoodsByIdYg(messagePresaleDTO.getGoodsId());
            if (goods == null){
                log.info("updateGoodsPresaleGoodsType()预售商品不存在{}",goods);
                return;
            }

            if (!messagePresaleDTO.getStartDate().equals(goods.getStartDate().getTime())){
                log.info("updateGoodsPresaleGoodsType()预售商品预售时间已更新{}",goods.getStartDate());
                return;
            }

            goods.setGoodsType("10");
            goodsService.updateGoods(goods);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
}
